<template>
  <div class="mui-pages" style="background-color: #fff;">
    <header class="mui-bar mui-bar-nav">
      <div class="header-common-title flex-justify-start">
        <a @click="fn.back()" href="javascript:void(0)"><img class="back-btn" src="../../../../static/images/back.png"></a>
        <div class="header-search flex-center">自己心得体会</div>
        <div @click="save()" class="header-right-btn flex-center">保存</div>
      </div>
    </header>
    <div class="mui-scroll-wrapper mui-page-content">
      <div class="mui-scroll">
        <div class="statistics-header" v-if="data.dealContent">
          <h4 v-if="false">{{scheduleDetail.insPartyMeetingResponseModel.subject}}心得</h4>
          <div class="experience-worlds" v-html="data.dealContent">
          </div>
        </div>
        <p class="record-item-title flex-justify-start">心得体会附件：</p>
        <ul class="list-item mui-content-padded flex-justify-start" v-if="data.dealFiles">
          <li class="enclosure-upload" v-for="(data,index) in getFilePath(data.dealFiles)" v-if="data" :key="data.fileId">
            <img v-if="isImage(data.fileName)" class="enclosure-upload-file" :src="data.url" @click="showImagePreview(data.url)" />
            <img v-if="!isImage(data.fileName)" class="enclosure-upload-file" src="../../../../static/images/up_document.png"  @click="downLoadFile(data)" />
            <p class="mui-ellipsis">{{data.fileName}}</p>
          </li>
        </ul>
        <ul class="mui-content-padded flex-justify-start">
          <cube-upload
            action=""
            :simultaneous-uploads="1"
            @files-added="uploadFile"
            @file-removed="fileRemoved"
          />
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
  import footerbar from '../common/footerbar.vue'
  import api from '@/common/config/api'
  import tools from '@/utils/tools'
  import loginService from '@/service/loginService'
  import scheduleSign from '@/components/work/schedule/scheduleSign'
  export default {
    components: {
      footerbar, scheduleSign
    },
    name: '',
    data () {
      return {
        fn: tools,
        data: {},
        attachmentList: [],
        tabIndex: 0,
        action: {
          target: api.updFiles,
          data: {
            fileType: 'appFile'
          }
        },
        options: {
          pullUpLoad: true,
          scrollbar: false
        },
        objectsName: '',
        swipeData: [],
        infinite: true,
        userInfo: this.$store.state.userInfo,
        isShowMoreBtn: false,
        scheduleDetail: {},
        pageIndex: 0
      }
    },
    created () {
      this.data = this.$store.state.otherExperience
      this.scheduleDetail = this.$store.state.scheduleDetail
      console.log(this.data)
    },
    methods: {
      showMoreBtn () {
        this.isShowMoreBtn = true
      },
      showDeal (item) {
        if (!item.dealFlag) {
          return false
        }
        this.$router.push({name: 'otherExperience'})
      },
      makeStr (arr) {
        return JSON.stringify(arr)
        let arrImg = []
        arr.forEach((v) => {
          arrImg.push(`{'fileId':'${v.fileId}','fileName':'${v.fileName}','totalBytes':${v.totalBytes}}`)
        })
        return `[${arrImg.join(',')}]`
      },
      // 将字符串转为数组
      getFileArrFromStr (str) {
        try {
          let arr = JSON.parse(str)
          arr.forEach((v, i) => {
            if (!v || v === 'null') {
              arr.splice(i, 1)
            }
          })
          return arr
        } catch (e) {
          return []
        }
      },
      // 保存心得
      save () {
        let id = this.data.id
        let oldFileArr = this.getFileArrFromStr(this.data.dealFiles)
        let data = {
          dealFiles: this.makeStr(this.attachmentList.concat(oldFileArr)),
          id: id
        }
        loginService.appSaveDealContentAndFile(data).then((res) => {
          if (res.code !== 200) {
            return tools.tip(res.message)
          }
          tools.back()
        })
      },
      // 删除文件
      fileRemoved (file) {
        this.attachmentList.some((v, i) => {
          if (v.fileName === file.file.name && v.fileSize === file.file.size) {
            this.attachmentList.splice(i, 1)
            return false
          }
        })
      },
      uploadFile (file) {
        let uploadFile = file[0]
        let formData = new FormData()
        formData.append('file', uploadFile)
        loginService.updFiles(formData).then((res) => {
          if (res.code !== 200) {
            return tools.tip(res.message)
          }
          this.attachmentList.push({'fileId': res.data[0].fileId, 'fileName': uploadFile.name, 'totalBytes': res.data[0].totalBytes})
        })
      },
      getFilePath (arr) {
        if (typeof arr === 'string') {
          try {
            arr = JSON.parse(arr)
          } catch (e) {
            console.error(e)
            arr = []
          }
        }
        console.log(arr)
        arr.map((v, i) => {
          if (!v) {
            arr.splice(i, 1)
          } else {
            v.url = api.downLoadFile + v.fileId
            return v
          }
        })
        return arr
      },
      isImage (fileName) {
        let arrExt = fileName.split('.')
        return 'PNG,JPG,JPEG,BMP,GIF'.split(',').indexOf(arrExt[arrExt.length - 1].toUpperCase()) > -1
      },
      showImagePreview (url) {
        if (url.length < 1) {
          return false
        }
        let imgs = [url]
        this.$createImagePreview({
          initialIndex: 0,
          imgs: imgs
        }, (h) => {
          return h('div', {
            class: {
              'image-preview-custom-header': false
            },
            slot: 'header'
          }, '')
        }).show()
      },
    }
  }
</script>
<style>
  .flex-justify-start {
    flex-wrap:wrap;
  }
  .enclosure-upload {
    position: relative;
    width: 25%;
    height: 120px;
    margin: 15px 0px 0 0;
    text-align: center;
  }

</style>
